// pages/components/backToBtn/backToBtn.js
var cf = require("../../config.js");
var cf2 = require("../../utils/config2");
var regeneratorRuntime = require("../../lib/js/runtime-module");
import formatDate from '../../utils/util2.js';
import Serv from './chatToBtnServ';
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 路徑
    url: {            // 属性名
      type: String,     // 类型（必填），目前接受的类型包括：String, Number, Boolean, Object, Array, null（表示任意类型）
      value: '/pages/index/index'     // 属性初始值（可选），如果未指定则会根据类型选择一个
    },
    title: {
      type: String,
      value: '回首页'
    },
    type: {
      type: String,
      value: 'tab'
    }

  },

  /**
   * 组件的初始数据
   */
  data: {
    buttonTop: 450,
    buttonLeft: 368,
    windowHeight: '',
    windowWidth: '',
    startPoint: '',
    currentIndex: null,
    current: 1,
    pageNo: 1,
    pageSize: 999,
    total: 0,
    phone: '',
    activityList: [],
    prodcutList: [],
    showVideo: false,  //控制是否显示video组件
    isPopping: false,
    isShowList:true,
    resetCurrent:0,
    selectName:'effect',
    selectBoxCurrent:0,
    imgUrls:[],
    videoImgArr:[],
    videoArr:[],
    vrImgArr:[],
    vrUrls:[],
    //楼盘分类列表
    categories:[
      {
        name:'效果图',
        value:'effect'
      },
      {
        name:'实景图',
        value:'realScene'
      },
      {
        name:'样板间',
        value:'sample'
      },
      {
        name:'规划图',
        value:'plan'
      },
      {
        name:'周边配套',
        value:'periphery'
      }
    ],
    isShowMZ:true,
    status:['可领取','已抢完','已领取','已领取'],
    isShowChatActive:false,
    isShowBoxSwiper:false
  },
  /**
   * 生命周期
   */
  lifetimes: {
    created() {
      wx.getSystemInfo({
        success: (res) => {
          // 高度,宽度 单位为px
          this.data.windowHeight = res.windowHeight;
          this.data.windowWidth = res.windowWidth;
        }
      });
    }
  },
 
  /**
   * 组件的方法列表
   */
  methods: {
    /**获取顾问信息 */
    getEmployeeInfo(cb) {
      var ctx = this;
      let cusmallToken = wx.getStorageSync('cusmallToken');
      let eId = wx.getStorageSync('eId');
      wx.request({
        url: cf.config.pageDomain + "/applet/mobile/visitcard/employee/getEmployeeInfo",
        data: {
          cusmallToken: cusmallToken,
          eid: eId
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          var data = res.data;
          var employee = data.model && data.model.employee
          if (employee) {
            if (cb) cb(employee)
          }
        }
      });
    },
    toPreview(e) {
      let productId = e.currentTarget.dataset.productid
      wx.navigateTo({
        url: `/subPackages/pages/preview/preview?productId=${productId}&action=1`,
      })
    },
    swiperChange(){
      if(this.data.currentIndex=='2'){
        let e={
          currentTarget:{
            dataset:{
              index:0,
              name:'effect'
            }
          }
        }
        this.selectTab(e)
      }
     
    },
      //获取点击楼盘分类栏索引
  selectTab:function(e){
    let {index,name} = e.currentTarget.dataset
    let { activityList } = this.data
    activityList[index][index]=activityList[index][name]
    this.setData({ resetCurrent: parseInt(index), selectName: name, activityList})
  },
    goDetail(e){
      let { channel,name,contentId,businessId } = e.currentTarget.dataset;
      if(this.data.currentIndex==3){
        wx.navigateTo({
          url:`/subPackages/pages/InformationDetail/InformationDetail?id=${contentId}&name=${name}`
         });
      }else if(this.data.currentIndex==4){
        if(channel !==4){
          wx.navigateTo({
            url:`/subPackages2/pages/findHouse/activity/apply/apply?contentId=${contentId}&productId=${businessId}`
          });
        }else{
         wx.navigateTo({
           url:`/subPackages/pages/giftManage/giftDetail/giftDetail?giftId=${contentId}`
         });
        }
      }
      
      
    },
    //播放视频
    playVideo(e) {
      //点击视频封面图,显示video组件并自动播放
      let index = e.currentTarget.dataset.index
      this.setData({
        showVideo: true,
        videoIndex: index
      })
      this.videoContext = wx.createVideoContext('myVideo' + index)
      this.videoContext.play()
    },
    //播放控件（播放/暂停按钮）
    onControlsPause(e) {
      let id = e.currentTarget.dataset.index;
      this.videoContext = wx.createVideoContext(`myVideo${id}`);
      if (this.data.play) {
        this.videoContext.play();
        this.setData({
          play: false
        });
      } else {
        this.videoContext.play();
      }
    },
    //获取楼盘下所有户型信息
  getAllhouseType: function (id,cb){
   Serv.queryHouseTypeList(id).then((res)=>{
    if (res.success) {
      let sampleList = []
     
      res.rows.map(item => {
        if (item.medias&&JSON.stringify(item.medias)!="{}"){
          sampleList.push(...item.medias.sample)
        }
      })
      if(cb)cb(sampleList) 
    }
    });

  },
    //获取顾问的楼盘
    async getEmployeeProduct() {
      let that = this;
      let { pageSize, pageNo, total, prodcutList, phone,isShowList,imgUrls,videoImgArr,videoArr,vrImgArr,vrUrls } = this.data
      wx.request({
        url: `${cf2.default.dataCenter}/zmzj/product/${phone}/${pageNo}/${pageSize}`,
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('authName')
        },
        success: function (res) {
          if (res.data.data && res.data.data.list.length > 0) {
            total = res.data.data.totalCount;
            let list = res.data.data.list;
            if (pageNo > 1) {//分页
              prodcutList = prodcutList.concat(list);
            } else {
              prodcutList = list
            }
          
         
          prodcutList.length > 0 && prodcutList.map((item, index) => {
            let imgArr = [],
                param = {};
                that.getAllhouseType(item.productId,(value)=>{
                  imgArr.push(...item.medias.effect)
                  param[index] = imgArr;
                  param.effect= item.medias.effect
                  param.realScene= item.medias.realScene
                  param.sample = value
                  param.plan = item.medias.plan
                  param.periphery = item.medias.periphery
                  param.productId=item.productId
                  param.pageNum = [item.medias.effect.length,item.medias.realScene.length,value.length,item.medias.plan.length,item.medias.periphery.length];
                  imgUrls.push(param);
                 
                  
              if (item.medias.video.length > 0) {
                let videParam = {};
                videParam.item = item.medias.video;
                videParam.name = item.name;
                videoArr.push(videParam);
                let imgArrEffect = item.medias.effect
                let videEffectParam = {}
                let arrTmp = []
                for (let i = 0; i < item.medias.video.length; i++) {
                  imgArrEffect.map(i => {
                    arrTmp.push(i)
                  })
                }
                if (arrTmp.length > item.medias.video.length) {
                  arrTmp.splice(item.medias.video.length, arrTmp.length - 1)
                }
                videEffectParam.item = arrTmp;
                videoImgArr.push(videEffectParam);
  
              }
              if (item.medias.vr.length > 0) {
                let vrParam = {};
                vrParam.item = item.medias.vr;
                vrParam.name = item.name;
                vrUrls.push(vrParam);
                let imgArrEffect = item.medias.effect
                let vrEffectParam = {}
                let vrTmp = []
  
                for (let i = 0; i < item.medias.vr.length; i++) {
                  imgArrEffect.map(i => {
                    vrTmp.push(i)
                  })
                }
                if (vrTmp.length > item.medias.vr.length) {
                  vrTmp.splice(item.medias.vr.length, vrTmp.length - 1)
                }
                vrEffectParam.item = vrTmp;
                vrImgArr.push(vrEffectParam);
              }
              that.setData({
                imgUrls, videoImgArr, videoArr, vrImgArr, vrUrls
                })
                });

          });
         
        }

        }
      })
    },
    //获取优惠券
     getCouponsList(){
        let { phone } = this.data;
        let that = this;
        wx.request({
          url: `${cf2.default.dataCenter}zmzj/coupon/${phone}`,//`${cf2.default.dataCenter}zmzj/coupon/${phone}`, //'http://10.73.159.105:8097/zmzj/coupon/15940067368',//
          header: {
            'content-type': 'application/json',
            'token': wx.getStorageSync('authName')
          },
          success: function (res) {
            console.log(res.data);
            let couponsList = []
            for (let key in res.data) {
              if (res.data[key].data && res.data[key].data.length) {
                res.data[key].data.map(item => {
                  item.productId = key;
                  couponsList.push(item);

                })
              }
            }
            that.setData({ couponsList })
  
          }
        })
    },
    //获取楼盘活动
    getHouseActivity: function (projectName) {
      let { pageSize, pageNo, activityList, total, phone } = this.data,
        that = this,
        activityData = [];
      wx.request({
        url: `${cf2.default.dataCenter}zmzj/${projectName}/${phone}/${pageNo}/${pageSize}`,
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('authName')
        },
        success: function (res) {
          if (res.data.data && res.data.data.list.length > 0) {
            total = res.data.data.totalCount;
            if(projectName=='news'){
              activityData = res.data.data.list && res.data.data.list.filter((item, idx) => {
                if (item.endDate) {
                  return item.endDate && formatDate.contrastDate(item.endDate);
                } else {
                  return item;
                }
              })
              activityData && activityData.sort((item, idx) => { return !item.isSelfTemplate });
            }else{
              activityData = res.data.data.list;
            }

           if (pageNo > 1) {//分页
              activityList = activityList.concat(activityData);
            } else {
              activityList = activityData
            }
          }
          let paramData = { total };
          paramData[projectName] = activityList
          that.setData(paramData)

        }
      })


    },
    goCouponRules: function(e) {
      let id = e.currentTarget.dataset.id // 优惠券活动id
      // wx.setStorageSync('dqcoupon', this.properties.coupon)
      wx.navigateTo({
        url: '/subPackages2/pages/my/myCoupons/couponsRules/couponsRules?id=' + id
      })
    },
    goCounp(){
      wx.navigateTo({
        url:'/subPackages2/pages/couponsList/couponsList'
      });
    },
    toVR(e) {
      let vrUrl = e.currentTarget.dataset.url
      wx.navigateTo({
        url: `/subPackages/pages/video/videoUrl?url=${vrUrl[0]}`,
      })
    },
    seletedTap(e) {
      let { name, seleted } = e.currentTarget.dataset;
      this.setData({ currentIndex: seleted,selectBoxCurrent:0, activityList: this.data[name],isShowBoxSwiper:true});
      this.seletedPopp();
      this.swiperChange();
    },
    routerMz(){
      this.setData({
        isShowMZ:false
      });
      this.triggerEvent('myRouterMz', {width:140,header:140})

      this.getEmployeeInfo((res) => {
        this.setData({
          phone: res.phone
        });
        this.getHouseActivity('activity');
        this.getHouseActivity('news');
        this.getEmployeeProduct();
        this.getCouponsList();
      })
    },
    router(e) {
      this.triggerEvent('myevent', {isPopping:!this.data.isPopping})
      let { isShowChatActive }  = this.data
      if(!this.data.isPopping){
        this.popp();
      }else{
        this.takeback();
      }
      this.setData({
        isShowChatActive:!isShowChatActive,
        isShowBoxSwiper:false
      })
    },
    seletedPopp(){
      let animationPlus = wx.createAnimation({
        duration: 100,
        timingFunction: "ease-in",
        delay: 0  //0则不延迟
      })
      animationPlus.opacity(1).left('auto').step();
      this.setData({
        animList: animationPlus.export()
      })
    },
    seletedTakeback(){
      let animationPlus = wx.createAnimation({
        duration: 100,
        timingFunction: "ease-in",
        delay: 0  //0则不延迟
      })
      animationPlus.opacity(0).left(3000).step();
      this.setData({
        animList: animationPlus.export()
      })
    },
    //弹出动画
    popp: function () {
      let animationPlus = wx.createAnimation({
        duration: 100,
        timingFunction: "ease-in",
        delay: 0  //0则不延迟
      })
      animationPlus.opacity(1).left('auto').step();
      this.setData({
        animPlus: animationPlus.export(),
        buttonLeft:310,
        isPopping:true
      })
    },

    //收回动画
    takeback: function () {
      let animationPlus = wx.createAnimation({
        duration: 100,
        timingFunction: "linear",
        delay: 0  //0则不延迟
      })
      animationPlus.opacity(0).left(3000).step();
      this.setData({
        animPlus: animationPlus.export(),
        isPopping:false,
        currentIndex:null
      })
      this.seletedTakeback();
    },
    //结束
    buttonEnd(){
      let that = this,timer,subtimer;
      timer= setTimeout(function () {
        that.setData({
          buttonLeft:310,
          isPopping:false
        });
       subtimer =setTimeout(function(){
          that.setData({
            buttonLeft:368,
            isPopping:false
          });
        }.bind(this), 3000);
      }.bind(this), 3000)
      that.setData({
        timer,subtimer
      });
    },
    buttonMove(){
     let { subtimer,timer} = this.data;
     clearTimeout(subtimer);
     clearTimeout(timer);
    },
    buttonStart(e) {
      this.setData({
        startPoint: e.changedTouches[0]
      })

    },
    buttonMove(e) {
      let endPoint = e.changedTouches[e.changedTouches.length - 1];
      let { startPoint } = this.data;
      let translateX = endPoint.clientX - startPoint.clientX
      let translateY = endPoint.clientY - startPoint.clientY

      this.setData({
        startPoint: endPoint
      })
      var buttonTop = this.data.buttonTop + translateY
      var buttonLeft = this.data.buttonLeft + translateX
      //判断是移动否超出屏幕
      if (buttonLeft + 67 >= this.data.windowWidth) {
        buttonLeft = this.data.windowWidth - 67;
      }
      if (buttonLeft <= 0) {
        buttonLeft = 0;
      }
      if (buttonTop <= 0) {
        buttonTop = 0
      }
      if (buttonTop + 67 >= this.data.windowHeight) {
        buttonTop = this.data.windowHeight - 67;
      }
      this.setData({
        buttonTop: buttonTop,
        buttonLeft: buttonLeft
      })

    }
  }
})
